<template>
  <view class="container">
    <uni-card>
      <!-- 搜索区域 -->
      <view class="uni-search">
        <uni-search-bar
          v-model="queryParams.dictName"
          placeholder="请输入字典名称"
          @confirm="handleQuery"
        />
      </view>
      
      <!-- 操作按钮区域 -->
      <view class="uni-group">
        <button type="primary" @click="handleAdd" size="mini">新增</button>
      </view>

      <!-- 列表区域 - 使用卡片布局 -->
      <view class="dict-list">
        <view 
          v-for="(item, index) in pageData" 
          :key="index" 
          class="dict-item"
        >
          <view class="dict-header">
            <view class="dict-icon">
              <uni-icons type="bars" size="20"></uni-icons>
            </view>
            <view class="dict-title">{{ item.dictName }}</view>
            <view class="dict-type">{{ item.dictType }}</view>
            <view class="dict-status" :class="item.status === '0' ? 'status-normal' : 'status-disabled'">
              {{ item.status === '0' ? '正常' : '停用' }}
            </view>
            <view class="dict-actions">
              <button type="primary" size="mini" @click.stop="handleData(item)" class="action-btn">数据</button>
              <button type="primary" size="mini" @click.stop="handleUpdate(item)" class="action-btn">修改</button>
              <button type="warn" size="mini" @click.stop="handleDelete(item)" class="action-btn">删除</button>
            </view>
          </view>
          <view class="dict-remark" v-if="item.remark">
            <text>{{ item.remark }}</text>
          </view>
        </view>
      </view>
      
      <!-- 分页控件 -->
      <view class="pagination" v-if="typeList.length > 0">
        <view class="pagination-info">
          显示 {{ startIndex + 1 }}-{{ endIndex }} 条，共 {{ typeList.length }} 条
        </view>
        <view class="pagination-btns">
          <button 
            class="pagination-btn" 
            :disabled="currentPage === 1" 
            :class="{ 'disabled': currentPage === 1 }"
            @click="changePage(currentPage - 1)"
          >
            <uni-icons type="left" size="14"></uni-icons>
          </button>
          
          <view class="page-numbers">
            <view 
              v-for="page in displayedPages" 
              :key="page" 
              class="page-number" 
              :class="{ 'active': currentPage === page }"
              @click="changePage(page)"
            >
              {{ page }}
            </view>
          </view>
          
          <button 
            class="pagination-btn" 
            :disabled="currentPage === totalPages" 
            :class="{ 'disabled': currentPage === totalPages }"
            @click="changePage(currentPage + 1)"
          >
            <uni-icons type="right" size="14"></uni-icons>
          </button>
        </view>
      </view>
      
      <!-- 无数据提示 -->
      <view class="empty-tip" v-if="typeList.length === 0">
        <uni-icons type="info" size="30" color="#999"></uni-icons>
        <text>暂无字典数据</text>
      </view>
    </uni-card>

    <!-- 添加或修改字典类型弹窗 -->
    <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        :title="title"
        mode="input"
        :value="form.dictName"
        placeholder="请输入字典名称"
        @confirm="submitForm"
      >
        <uni-forms ref="form" :model="form" :rules="rules">
          <uni-forms-item label="字典名称" required name="dictName">
            <uni-easyinput v-model="form.dictName" placeholder="请输入字典名称"/>
          </uni-forms-item>
          <uni-forms-item label="字典类型" required name="dictType">
            <uni-easyinput v-model="form.dictType" placeholder="请输入字典类型"/>
          </uni-forms-item>
          <uni-forms-item label="状态" name="status">
            <uni-data-checkbox
              v-model="form.status"
              :localdata="[
                {text: '正常', value: '0'},
                {text: '停用', value: '1'}
              ]"
            />
          </uni-forms-item>
          <uni-forms-item label="备注" name="remark">
            <uni-easyinput v-model="form.remark" type="textarea" placeholder="请输入备注"/>
          </uni-forms-item>
        </uni-forms>
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import { listType, getType, delType, addType, updateType } from '@/api/system/dict/type'

export default {
  data() {
    return {
      // 遮罩层
      loading: true,
      // 字典类型列表
      typeList: [],
      // 弹出层标题
      title: "",
      // 查询参数
      queryParams: {
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictName: {
          rules: [{
            required: true,
            errorMessage: '字典名称不能为空'
          }]
        },
        dictType: {
          rules: [{
            required: true,
            errorMessage: '字典类型不能为空'
          }]
        }
      },
      // 分页参数
      pageSize: 5,
      currentPage: 1
    };
  },
  computed: {
    // 总页数
    totalPages() {
      return Math.ceil(this.typeList.length / this.pageSize);
    },
    // 当前页数据
    pageData() {
      const start = (this.currentPage - 1) * this.pageSize;
      const end = start + this.pageSize;
      return this.typeList.slice(start, end);
    },
    // 显示的页码
    displayedPages() {
      const pages = [];
      const maxVisiblePages = 5;
      
      if (this.totalPages <= maxVisiblePages) {
        // 页数少于最大显示页数，显示所有页
        for (let i = 1; i <= this.totalPages; i++) {
          pages.push(i);
        }
      } else {
        // 页数多于最大显示页数，显示部分页
        let startPage = Math.max(1, this.currentPage - 2);
        let endPage = Math.min(this.totalPages, startPage + maxVisiblePages - 1);
        
        // 调整起始页，确保显示5个页码
        if (endPage - startPage < maxVisiblePages - 1) {
          startPage = Math.max(1, endPage - maxVisiblePages + 1);
        }
        
        for (let i = startPage; i <= endPage; i++) {
          pages.push(i);
        }
      }
      
      return pages;
    },
    // 起始索引
    startIndex() {
      return (this.currentPage - 1) * this.pageSize;
    },
    // 结束索引
    endIndex() {
      return Math.min(this.startIndex + this.pageSize, this.typeList.length);
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询字典类型列表 */
    getList() {
      this.loading = true;
      listType(this.queryParams).then(response => {
        this.typeList = response.rows;
        this.currentPage = 1; // 重置为第一页
        this.loading = false;
      });
    },
    /** 切换页码 */
    changePage(page) {
      if (page >= 1 && page <= this.totalPages) {
        this.currentPage = page;
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.title = "添加字典类型";
      this.$refs.popup.open();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getType(row.dictId).then(response => {
        this.form = response.data;
        this.title = "修改字典类型";
        this.$refs.popup.open();
      });
    },
    /** 查看字典数据按钮操作 */
    handleData(row) {
      uni.navigateTo({
        url: '/pages/system/dict/data?dictId=' + row.dictId + '&dictType=' + row.dictType
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs.form.validate().then(res => {
        if (this.form.dictId != undefined) {
          updateType(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$refs.popup.close();
            this.getList();
          });
        } else {
          addType(this.form).then(response => {
            this.$modal.msgSuccess("新增成功");
            this.$refs.popup.close();
            this.getList();
          });
        }
      }).catch(error => {
        console.log('表单错误信息：', error);
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      uni.showModal({
        title: '提示',
        content: '是否确认删除名称为"' + row.dictName + '"的数据项?',
        success: res => {
          if (res.confirm) {
            delType(row.dictId).then(() => {
              this.getList();
              this.$modal.msgSuccess("删除成功");
            })
          }
        }
      });
    },
    // 表单重置
    reset() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: '0',
        remark: undefined
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.container {
  padding: 20rpx;
}
.uni-search {
  padding: 10rpx 0;
}
.uni-group {
  margin: 20rpx 0;
  display: flex;
  justify-content: flex-end;
}

.dict-list {
  margin-top: 15px;
}

.dict-item {
  margin-bottom: 12px;
  border-radius: 8px;
  background-color: #f9f9f9;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  overflow: hidden;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.dict-header {
  display: flex;
  align-items: center;
  padding: 12px;
  background-color: #fff;
}

.dict-icon {
  margin-right: 10px;
  display: flex;
  align-items: center;
}

.dict-title {
  flex: 1;
  font-weight: bold;
  font-size: 14px;
}

.dict-type {
  color: #606266;
  font-size: 12px;
  background-color: #f0f2f5;
  padding: 2px 6px;
  border-radius: 4px;
  margin-right: 10px;
}

.dict-status {
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 11px;
  margin-right: 10px;
}

.status-normal {
  background-color: #e8f7e9;
  color: #67c23a;
}

.status-disabled {
  background-color: #f4f4f5;
  color: #909399;
}

.dict-actions {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-btn {
  padding: 0 8px;
  height: 24px;
  line-height: 24px;
  font-size: 11px;
  margin-left: 0 !important;
}

.dict-remark {
  padding: 8px 12px;
  font-size: 12px;
  color: #909399;
  background-color: #f9f9f9;
  border-top: 1px dashed #eee;
  
  text {
    word-break: break-all;
  }
}

.empty-tip {
  padding: 30px 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #999;
  
  text {
    margin-top: 10px;
    font-size: 14px;
  }
}

// 美化卡片样式
:deep(.uni-card) {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  border-radius: 8px;
}

// 美化搜索框
:deep(.uni-searchbar) {
  padding: 5px 0;
}

// 美化按钮悬停效果
button.action-btn:active {
  opacity: 0.8;
}

.pagination {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 10px 0;
}

.pagination-info {
  font-size: 12px;
  color: #909399;
  margin-bottom: 10px;
}

.pagination-btns {
  display: flex;
  align-items: center;
}

.pagination-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  padding: 0;
  margin: 0 5px;
  background-color: #f4f4f5;
  border: none;
  border-radius: 4px;
  
  &.disabled {
    opacity: 0.5;
    pointer-events: none;
  }
  
  &:active {
    background-color: #e9e9eb;
  }
}

.page-numbers {
  display: flex;
  align-items: center;
}

.page-number {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
  margin: 0 2px;
  font-size: 14px;
  color: #606266;
  border-radius: 4px;
  cursor: pointer;
  
  &:active {
    background-color: #e9e9eb;
  }
  
  &.active {
    background-color: #409eff;
    color: #fff;
  }
}
</style> 